package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户喜欢服务接口实现类
 */
@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private FriendApi friendApi;

    /**
     * 喜欢 或 不喜欢 记录
     *
     * @param userLike
     * @return
     */
    @Override
    public boolean save(UserLike userLike) {
        Long userId = userLike.getUserId();//当前登录用户id
        Long likeUserId = userLike.getLikeUserId();//喜欢的用户id
        Boolean isLike = userLike.getIsLike();//是否喜欢 左滑右滑
        long nowTime = System.currentTimeMillis();//时间
        //1.根据当前登录用户id 喜欢的用户id 查询记录是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        if (mongoTemplate.exists(query, UserLike.class)) {
            //2.存在 则更新记录
            Update update = new Update();
            update.set("isLike", isLike);//是否喜欢
            update.set("updated", nowTime);//更新时间
            mongoTemplate.updateFirst(query, update, UserLike.class);
        } else {
            //3.不存在 则保存记录
            userLike.setCreated(nowTime);
            userLike.setUpdated(nowTime);
            mongoTemplate.insert(userLike);
        }
        //4.如果isLike=true，判断对方是否喜欢登录用户
        if (isLike) {
            Query query2 = new Query();
            query2.addCriteria(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId).and("isLike").is(true));
            UserLike ul = mongoTemplate.findOne(query2, UserLike.class);
            //4.1如果喜欢 将好友关系添加好友表 return true;
            if (mongoTemplate.exists(query2, UserLike.class)) {
                friendApi.makeFriends(userId, likeUserId);
                return true;
            }
        }
        return false;
    }

    /**
     * 小视频-撤销关注
     * @param uid
     * @param userId
     */
    @Override
    public void delete(Long uid, Long userId) {
        Query query = new Query(Criteria.where("likeUserId").is(uid).and("userId").is(userId));
        mongoTemplate.remove(query,UserLike.class);
    }


    /**
     * 查询我喜欢的
     * @param userId
     * @return
     */
    @Override
    public Integer findById(Long userId) {

        Query query =  new Query(Criteria.where("userId").is(userId).and("isLike").is(true));
        Integer count = Math.toIntExact(mongoTemplate.count(query, UserLike.class));
        return count;
    }


    /**
     * 查询 我的粉丝（喜欢我的）
     * @param userId
     * @return
     */
    @Override
    public Integer findByIds(Long userId) {
        Query query =  new Query(Criteria.where("likeUserId").is(userId).and("isLike").is(true));
        Integer count = Math.toIntExact(mongoTemplate.count(query, UserLike.class));
        return count;
    }


    /**
     * 查询是否喜欢
     * @param id
     * @param userId
     * @return
     */
    @Override
    public Boolean findAlreadyLove(Long id, Long userId) {

        Query query = new Query(Criteria.where("userId").is(id).and("toUserId").is(userId));
        UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
        Boolean isLike =false;
        if (userLike !=null) {
             isLike = userLike.getIsLike();

        }
        return isLike;
    }

    /**
     * 分页查询互相喜欢对象
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult findPage1(Long page, Long pageSize, Long userId) {
        //定义返回PageResult<UserLike>
        PageResult<Friend> pageResult = new PageResult<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("isLike").is(true));
        //1查询总记录数
        long counts = mongoTemplate.count(query, UserLike.class);
        long start = (page-1)*pageSize;
        //2查询当前页面需要展示的数据
        List<UserLike> userLikeList = new ArrayList<>();
        if(counts > start){ //20 > 27
            //构造分页limit 0,3
            query.limit(pageSize.intValue());//每页查询几条
            query.skip(start);//跳过1条数据
            //query.with(PageRequest.of(page,pageSize));
            query.with(Sort.by(Sort.Direction.DESC,"userId"));
            userLikeList = mongoTemplate.find(query, UserLike.class);
        }
        return new PageResult<>(page,pageSize,counts,userLikeList);
    }

    /**
     * 分页查询互相喜欢对象
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult findPage2(Long page, Long pageSize, Long userId) {
        //定义返回PageResult<UserLike>
        PageResult<Friend> pageResult = new PageResult<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("likeUserId").is(userId).and("isLike").is(true));
        //1查询总记录数
        long counts = mongoTemplate.count(query, UserLike.class);
        long start = (page-1)*pageSize;
        //2查询当前页面需要展示的数据
        List<UserLike> userLikeList = new ArrayList<>();
        if(counts > start){ //20 > 27
            //构造分页limit 0,3
            query.limit(pageSize.intValue());//每页查询几条
            query.skip(start);//跳过1条数据
            //query.with(PageRequest.of(page,pageSize));
            query.with(Sort.by(Sort.Direction.DESC,"userId"));
            userLikeList = mongoTemplate.find(query, UserLike.class);
        }
        return new PageResult<>(page,pageSize,counts,userLikeList);
    }

    /**
     * 根据userId查询我的关注
     * @param userId
     * @return
     */
    @Override
    public List<Long> findByUserId1(Long userId) {

        Query query = new Query(Criteria.where("userId").is(userId).and("isLike").is(true));
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        List<Long> list = userLikeList.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        return list;
    }

    /**
     * 查找我的粉丝
     * @param userId
     * @return
     */
    @Override
    public List<Long> findByUserId2(Long userId) {

        Query query = new Query(Criteria.where("likeUserId").is(userId).and("isLike").is(true));
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);

        List<Long> list = userLikeList.stream().map(UserLike::getUserId).collect(Collectors.toList());
        return list;
    }
}
